package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ReadBehaviorDto;
import com.heima.behavior.pojos.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Gareth Cao
 * @date 2022/6/25 12:20
 */
@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 阅读行为不需要回显和查询，不需要存入redis，因此只需要存入到mongo当中就行
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //1 校验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2 获取用户登录id
        ApUser apUser = ApThreadLocalUtil.getUser();
        if (apUser == null) {
            //未登录
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (apUser.getId() == 0) {
            //游客
            return ResponseResult.errorResult(AppHttpCodeEnum.VISITOR_NEED_LOGIN);
        }
        //3 查询mongo中是否有数据，有就更新次数，没有就新增
        Query query = Query.query(Criteria.where("userId").is(apUser.getId())
                .and("articleId").is(dto.getArticleId()));
        ApReadBehavior readBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
        if (readBehavior == null) {
            //mongo中没有
            readBehavior = new ApReadBehavior(); //必须要new，否则就是空指针异常
            BeanUtils.copyProperties(dto, readBehavior);
            readBehavior.setId(ObjectId.get().toHexString());
            readBehavior.setUserId(apUser.getId().longValue());
            readBehavior.setCount(1);
            readBehavior.setCreatedTime(new Date());
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setCount(1);
        } else {
            //mongo中存在，修改
            readBehavior.setCount(dto.getCount() + readBehavior.getCount());
            readBehavior.setUpdatedTime(new Date());
        }
        //save方法有就修改，没有就新增
        mongoTemplate.save(readBehavior);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
